package com.meter.data.listener;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.meter.basic.domain.BasicMeter;
import com.meter.basic.service.IBasicMeterService;
import com.meter.basic.service.impl.BasicMeterServiceImpl;
import com.meter.common.manager.AsyncManager;
import com.meter.common.utils.DateUtils;
import com.meter.common.utils.HexUtils;
import com.meter.common.utils.StringUtils;
import com.meter.common.utils.spring.SpringUtils;
import com.meter.data.domain.MeterData;
import com.meter.data.protocol.result.Meter01;
import com.meter.data.protocol.result.Meter02;
import com.meter.data.protocol.result.Meter03;
import com.meter.data.protocol.result.Meter04;
import com.meter.data.service.IMeterDataService;
import com.meter.redis.service.RedisService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class MeterDataListener {

    @Autowired
    private RedisService redisService;

    @Autowired
    private IBasicMeterService basicMeterService;

    @Autowired
    private IMeterDataService meterDataService;

    @RabbitListener(queues = {"result_queue"})
    @RabbitHandler
    public void resultQueueReceive(JSONObject jsonObject, Channel channel, Message message) {
        try {
            String messageId = message.getMessageProperties().getHeaders().get("spring_returned_message_correlation").toString();
            if (redisService.hasKey("message:" + messageId))
                return;
            redisService.set("message:" + messageId, messageId, 10L);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            String[] msgs = HexUtils.strChange(jsonObject.getString("msg"), 2);
            String meterNo = HexUtils.strChangeStrByLength(msgs, 3, 4, false);
            BasicMeter basicMeter = basicMeterService.getOne(Wrappers.lambdaQuery(BasicMeter.class).eq(BasicMeter::getMeterNo, meterNo).last("limit 1"));
            if(StringUtils.isNotNull(basicMeter)) {
                MeterData meterData = meterDataService.selectMeterDataByMeterId(basicMeter.getMeterId());
                if(StringUtils.isNotNull(meterData)) {
                    meterData.setMeterNo(basicMeter.getMeterNo());
                    meterData.setReturnOrder(jsonObject.getString("msg"));
                    meterData.setReturnFlag("1");
                    meterData.setReadingTime(DateUtils.getNowDate());
                    int dataLength = HexUtils.get10HexNum(msgs[9] + msgs[10]);
                    String[] contents = HexUtils.strChangeByLength(msgs, 11, dataLength);
                    if (basicMeter.getMeterFactory().equals("01")) {
                        log.info("保存兰吉尔热表数据");
                        AsyncManager.me().execute(() -> {
                            Meter01.saveMeter(contents, meterData);
                        });
                    } else if (basicMeter.getMeterFactory().equals("02")) {
                        log.info("保存恩乐曼热表数据");
                        AsyncManager.me().execute(() -> {
                            Meter02.saveMeter(contents, meterData);
                        });
                    } else if (basicMeter.getMeterFactory().equals("03")) {
                        log.info("保存代傲热表数据");
                        AsyncManager.me().execute(() -> {
                            Meter03.saveMeter(contents, meterData);
                        });
                    } else if (basicMeter.getMeterFactory().equals("04")) {
                        log.info("保存金水热表数据");
                        AsyncManager.me().execute(() -> {
                            Meter04.saveMeter(contents, meterData);
                        });
                    }
                } else {
                    log.error("抄表记录更新失败，没有对应的抄表记录：" + jsonObject.toJSONString());
                }
            } else {
                log.error("抄表记录更新失败，没有对应的表信息：" + jsonObject.toJSONString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
